from time import time
from symbide import PATHS
from symbide.src.utils import createUniquePath
from os.path import join, exists
from os import remove

class ExecutionLogger:
    def __init__(self):
        self.log = []
        self.dir = PATHS['log_executor']
        self.startTime = ''
        self.endTime = ''
    
    def _getLogfilesIndex(self):
        '''
        Returns a list of the logfiles listed in index.txt.
        '''
        
        self.index = join(self.dir, 'index.txt')
        if exists(self.index):
            f = file(self.index, 'r')
            logfiles = f.read().split('\n')
            f.close()
        else:
            logfiles=[]
        return logfiles
    
    def _writeLogfilesIndex(self, logfiles):
        '''
        Lists the last 10 logfiles in index.txt and removes all
        older logfiles. 
        '''
        
        if len(logfiles)>10:
            old_logs = logfiles[10:]
            for i in old_logs:
                path = i.split(' : ', 2)[0]
                if exists(path):
                    remove(path)
            logfiles[10:] = []
        f = file(self.index, 'w')
        f.write('\n'.join(logfiles))
        f.close()
        
    def saveLogfile(self, text):
        '''
        Saves the logfile to an unique path into the 'log_executor' directory.
        '''
        
        p = createUniquePath(self.dir, 'execution', '.txt')
        f = file(p, 'w')
        string = '\n\n<session starttime="%s" endtime="%s">%s</session>'
        f.write(string%(self.startTime, self.endTime, text))
        f.close()
        return p
        
    def start(self):
        self.startTime = time()
        self.endTime = ''
        self.log = []
        self.has_started = True
        
    def __call__(self, text):
        if self.has_started:
            self.log.append(text)
        
    def end(self):
        self.endTime = time()
        text = ''.join(self.log).strip(' \n\t')
        p = self.saveLogfile(text)
                       
        logfiles = self._getLogfilesIndex()
        logfiles.insert(0,'%s : %s'%(p, self.startTime))
        self._writeLogfilesIndex(logfiles)
